'use strict';

const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");

function getNpmInfo(npmName,regis) {
    if(!npmName) return null;
    const registry = regis || getDefaultRegistry();
    const npmInfoUrl = urlJoin(registry,npmName);
    return axios.get(npmInfoUrl).then(response=>{
        if(response.status===200){
          return response?.data;
        }
        else{
            return undefined;
        } 
    }).catch(err=>{
       return Promise.reject(err);
    })
}
function getDefaultRegistry(isOriginal = false){
    return isOriginal ? "https://registry.npmjs.org":"https://registry.npm.taobao.org";
}

async function getNpmVersions(npmName,registry){
    const data =await getNpmInfo(npmName,registry);
    if(data){
        return Object.keys(data.versions);
    }else{
        return [];
    }
}

function getNpmSemverVersions(baseVersion,versions){
    //^表示大于的意思
    versions = versions
    .filter(version=>semver.satisfies(version,`^${baseVersion}`))
    .sort((a,b)=>semver.gt(b,a));
    return versions;
}
async function getNpmSemverVersion(baseVersion,npmName,registry){
    const versions = await getNpmVersions(npmName,registry); 
    const newVersions = getNpmSemverVersions(baseVersion,versions);
    if(Array.isArray(newVersions) && newVersions.length>0){
        return newVersions[0];
    }
    return null;
}
module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersions,
    getNpmSemverVersion
}